package com.ldl.exam.controller;

import com.ldl.exam.constant.Constants;
import com.ldl.exam.entity.Stu;
import com.ldl.exam.exception.ExamException;
import com.ldl.exam.service.StuService;
import com.ldl.exam.util.AjaxResult;
import com.ldl.exam.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @author liudaolin
 * @version 1.0
 * @date 2022/10/02 15:21:44
 */
@RestController
@RequestMapping("/front/stu")
public class StuController {
    @Autowired
    private StuService stuService;

    // 登录 已测试
    @RequestMapping("/login")
    public AjaxResult login(String loginName, String pwd, HttpSession session) {
        // TODO:
        if(CommonUtil.isEmpty(loginName)) {
            throw new ExamException("登录名不能为空");
        }
        if(CommonUtil.isEmpty(pwd)) {
            throw new ExamException("密码不能为空");
        }

        Stu login = stuService.login(loginName, pwd);
        login.setPwd(CommonUtil.randomUUID());// 作为随机 token
        session.setAttribute(Constants.STU_LOGIN_KEY, login);
        return AjaxResult.isOk("登录成功", login);
    }

    // 已测试
    @RequestMapping("/register")
    public AjaxResult register(Stu stu, String rePwd, HttpSession session) {
        // TODO:
        if(CommonUtil.isEmpty(stu.getLoginName())) {
            throw new ExamException("登录名不能为空");
        }
        if(CommonUtil.isEmpty(stu.getPwd())) {
            throw new ExamException("密码不能为空");
        }
        Date d = new Date();
        stu.setCreateDate(d);
        stu.setStatus(Constants.STU_OK);

        stuService.register(stu, rePwd);

        return AjaxResult.isOk("注册成功");
    }

    // 退出 已测试
    @RequestMapping("/logout")
    public AjaxResult logout(HttpSession session) {
        session.invalidate();
        return AjaxResult.isOk("退出成功");
    }

    // 修改学生基本信息
    @RequestMapping("/modifyStuInfo")
    public AjaxResult modifyStuInfo(Stu stu, HttpSession session) {
        // 必须登录才能修改
        // TODO: 格式验证
        stuService.modifyStuInfo(stu);
        return AjaxResult.isOk("修改成功");
    }

    // 修改学生密码
    @RequestMapping("/modifyPwd")
    public AjaxResult modifyPwd(Integer stuId, String oldPwd, String newPwd, String rePwd, HttpSession session) {
        Stu stu = (Stu) session.getAttribute(Constants.STU_LOGIN_KEY);
        // 必须登录, 并且 oldPwd 正确, 才能修改
        stuService.modifyPwd(stu.getId(), oldPwd, newPwd, rePwd);
        return AjaxResult.isOk("修改成功");
    }
}
